package java0325;

import java.util.Arrays;
import java.util.Stack;

public class Test {

    // 递归写法，快速排序
    public static void quickSort(int[] arr) {
        _quickSort(arr, 0, arr.length - 1);
    }

    private static void _quickSort(int[] arr, int begin, int end) {
        if (begin >= end) {
            return;
        }
        int index = partition(arr, begin, end);
        _quickSort(arr, 0, index - 1);
        _quickSort(arr, index + 1, end);
    }

    private static int partition(int[] arr, int begin, int end) {
        int left = begin;
        int right = end;
        int v = arr[end];
        while (left < right) {
            while (left < right && arr[left] < v) {
                left++;
            }
            while (left < right && arr[right] >= v) {
                right--;
            }
            swap(arr, right, left);
        }
        swap(arr, right, end);
        return right;
    }

    private static void swap(int[] arr, int index1, int index2) {
        int tmp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = tmp;
    }

    // 非递归写法，快速排序
    public static void quickSort2(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        stack.push(arr.length - 1);
        while (stack.isEmpty() == false) {
            int right = stack.pop();
            int left = stack.pop();
            if (left >= right) {
                continue;
            }
            int mid = partition(arr, left, right);
            stack.push(left);
            stack.push(mid - 1);
            stack.push(mid + 1);
            stack.push(right);
        }
    }

    public static void main(String[] args) {
        int[] arr = {4,9,5,2,7,6,4,8,1,3};
        quickSort2(arr);
        System.out.println(Arrays.toString(arr));
    }
}
